#!/bin/bash

# 定义颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

echo -e "${CYAN}=== Maxwell数据库连接配置 ===${NC}"
echo "时间: $(date)"
echo "=================================="

# 数据库连接参数
DB_HOST="192.168.10.102"
DB_PORT="3306"
DB_USER="root"
DB_PASS="123456"
DB_NAME="test"  # 您的数据库名称

# Maxwell安装路径
MAXWELL_HOME="/opt/maxwell"
MAXWELL_VERSION="1.42.2"

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误: 此脚本需要root权限运行${NC}"
        echo "请使用: sudo $0"
        exit 1
    fi
}

# 检查Java环境
check_java() {
    echo -e "${YELLOW}检查Java环境...${NC}"
    
    if command -v java &> /dev/null; then
        java_version=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
        echo -e "${GREEN}✓ Java已安装: $java_version${NC}"
    else
        echo -e "${RED}✗ Java未安装${NC}"
        echo "请先安装Java 8或更高版本"
        exit 1
    fi
}

# 下载和安装Maxwell
install_maxwell() {
    echo -e "${YELLOW}下载和安装Maxwell...${NC}"
    
    # 创建安装目录
    mkdir -p /opt
    cd /opt
    
    # 下载Maxwell
    if [ ! -f "maxwell-${MAXWELL_VERSION}.tar.gz" ]; then
        echo "下载Maxwell ${MAXWELL_VERSION}..."
        wget https://github.com/zendesk/maxwell/releases/download/v${MAXWELL_VERSION}/maxwell-${MAXWELL_VERSION}.tar.gz
    fi
    
    # 解压安装
    if [ -d "maxwell-${MAXWELL_VERSION}" ]; then
        rm -rf maxwell-${MAXWELL_VERSION}
    fi
    
    tar -xzf maxwell-${MAXWELL_VERSION}.tar.gz
    mv maxwell-${MAXWELL_VERSION} maxwell
    
    # 设置权限
    chown -R root:root /opt/maxwell
    chmod -R 755 /opt/maxwell
    
    echo -e "${GREEN}✓ Maxwell安装完成${NC}"
}

# 配置数据库用户权限
setup_database_permissions() {
    echo -e "${YELLOW}配置数据库用户权限...${NC}"
    
    # 创建maxwell用户
    mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "
    CREATE USER IF NOT EXISTS 'maxwell'@'%' IDENTIFIED BY 'maxwell';
    " 2>/dev/null
    
    # 授予必要权限
    mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "
    GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'maxwell'@'%';
    CREATE DATABASE IF NOT EXISTS maxwell;
    GRANT INSERT, UPDATE, DELETE, CREATE, ALTER, DROP ON maxwell.* TO 'maxwell'@'%';
    FLUSH PRIVILEGES;
    " 2>/dev/null
    
    echo -e "${GREEN}✓ 数据库权限配置完成${NC}"
}

# 生成Maxwell配置文件
generate_config() {
    echo -e "${YELLOW}生成Maxwell配置文件...${NC}"
    
    cat > /opt/maxwell/config.properties << EOF
# Maxwell配置文件
# 数据库连接配置
host=$DB_HOST
port=$DB_PORT
user=maxwell
password=maxwell

# 输出配置 (选择一种)
# 1. 输出到Kafka
producer=kafka
kafka.bootstrap.servers=localhost:9092
kafka_topic=maxwell_events

# 2. 输出到文件 (取消注释使用)
# producer=file
# output_file=/tmp/maxwell_events.json

# 3. 输出到Redis (取消注释使用)
# producer=redis
# redis_host=localhost
# redis_port=6379

# 4. 输出到RabbitMQ (取消注释使用)
# producer=rabbitmq
# rabbitmq_host=localhost
# rabbitmq_port=5672
# rabbitmq_user=guest
# rabbitmq_password=guest
# rabbitmq_exchange=maxwell
# rabbitmq_routing_key_template=%db%.%table%

# 过滤配置
# 包含特定数据库和表
# filter=include:$DB_NAME.*,include:test.*

# 排除特定数据库和表
# filter=exclude:*.*,include:$DB_NAME.*

# 输出配置
output_ddl=true
output_type=json
include_binlog_position=true
include_commit_info=true
include_null_fields=true
include_server_id=true
include_thread_id=true

# 性能配置
replication_heartbeat_period=3
replication_heartbeat_timeout=10
replication_heartbeat_retries=3

# 日志配置
log_level=info
EOF
    
    echo -e "${GREEN}✓ Maxwell配置文件已生成: /opt/maxwell/config.properties${NC}"
}

# 测试数据库连接
test_connection() {
    echo -e "${YELLOW}测试数据库连接...${NC}"
    
    # 测试maxwell用户连接
    mysql -h$DB_HOST -P$DB_PORT -umaxwell -pmaxwell -e "SELECT 1;" 2>/dev/null
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ maxwell用户连接成功${NC}"
    else
        echo -e "${RED}✗ maxwell用户连接失败${NC}"
        return 1
    fi
    
    # 检查binlog配置
    BINLOG_ENABLED=$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SHOW VARIABLES LIKE 'log_bin';" 2>/dev/null | grep "log_bin" | awk '{print $2}')
    if [ "$BINLOG_ENABLED" = "ON" ]; then
        echo -e "${GREEN}✓ binlog已开启${NC}"
    else
        echo -e "${RED}✗ binlog未开启${NC}"
        return 1
    fi
    
    # 检查数据库是否存在
    DB_EXISTS=$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name='$DB_NAME';" 2>/dev/null | tail -1)
    if [ "$DB_EXISTS" -eq 1 ]; then
        echo -e "${GREEN}✓ 数据库 $DB_NAME 存在${NC}"
    else
        echo -e "${YELLOW}⚠ 数据库 $DB_NAME 不存在，将创建${NC}"
        mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "CREATE DATABASE IF NOT EXISTS $DB_NAME;" 2>/dev/null
    fi
}

# 创建启动脚本
create_startup_script() {
    echo -e "${YELLOW}创建启动脚本...${NC}"
    
    cat > /opt/maxwell/start_maxwell.sh << 'EOF'
#!/bin/bash

# Maxwell启动脚本
MAXWELL_HOME="/opt/maxwell"
CONFIG_FILE="$MAXWELL_HOME/config.properties"
LOG_FILE="$MAXWELL_HOME/maxwell.log"

echo "=== 启动Maxwell ==="
echo "时间: $(date)"
echo "配置文件: $CONFIG_FILE"

# 检查Maxwell是否已安装
if [ ! -f "$MAXWELL_HOME/bin/maxwell" ]; then
    echo "错误: Maxwell未安装或路径不正确"
    exit 1
fi

# 检查配置文件
if [ ! -f "$CONFIG_FILE" ]; then
    echo "错误: 配置文件 $CONFIG_FILE 不存在"
    exit 1
fi

# 检查是否已在运行
if pgrep -f "maxwell" > /dev/null; then
    echo "Maxwell已在运行，PID: $(pgrep -f maxwell)"
    exit 1
fi

# 启动Maxwell
echo "启动Maxwell..."
cd "$MAXWELL_HOME"
nohup ./bin/maxwell --config="$CONFIG_FILE" > "$LOG_FILE" 2>&1 &

# 等待启动
sleep 3

# 检查启动状态
if pgrep -f "maxwell" > /dev/null; then
    echo "✓ Maxwell启动成功，PID: $(pgrep -f maxwell)"
    echo "日志文件: $LOG_FILE"
else
    echo "✗ Maxwell启动失败"
    echo "请检查日志: tail -f $LOG_FILE"
    exit 1
fi
EOF
    
    chmod +x /opt/maxwell/start_maxwell.sh
    
    # 创建停止脚本
    cat > /opt/maxwell/stop_maxwell.sh << 'EOF'
#!/bin/bash

echo "=== 停止Maxwell ==="
echo "时间: $(date)"

MAXWELL_PID=$(pgrep -f maxwell)

if [ ! -z "$MAXWELL_PID" ]; then
    echo "停止Maxwell进程: $MAXWELL_PID"
    kill $MAXWELL_PID
    sleep 3
    
    if pgrep -f maxwell > /dev/null; then
        echo "强制停止Maxwell..."
        kill -9 $MAXWELL_PID
    fi
    
    echo "✓ Maxwell已停止"
else
    echo "Maxwell未运行"
fi
EOF
    
    chmod +x /opt/maxwell/stop_maxwell.sh
    
    echo -e "${GREEN}✓ 启动和停止脚本已创建${NC}"
}

# 创建测试脚本
create_test_script() {
    echo -e "${YELLOW}创建测试脚本...${NC}"
    
    cat > /opt/maxwell/test_maxwell.sh << EOF
#!/bin/bash

echo "=== Maxwell连接测试 ==="
echo "时间: \$(date)"

# 测试数据库连接
echo "1. 测试数据库连接..."
mysql -h$DB_HOST -P$DB_PORT -umaxwell -pmaxwell -e "SELECT 1;" 2>/dev/null
if [ \$? -eq 0 ]; then
    echo "✓ 数据库连接成功"
else
    echo "✗ 数据库连接失败"
    exit 1
fi

# 检查binlog
echo "2. 检查binlog配置..."
BINLOG_ENABLED=\$(mysql -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASS -e "SHOW VARIABLES LIKE 'log_bin';" 2>/dev/null | grep "log_bin" | awk '{print \$2}')
if [ "\$BINLOG_ENABLED" = "ON" ]; then
    echo "✓ binlog已开启"
else
    echo "✗ binlog未开启"
fi

# 检查maxwell数据库
echo "3. 检查maxwell数据库..."
mysql -h$DB_HOST -P$DB_PORT -umaxwell -pmaxwell -e "USE maxwell; SHOW TABLES;" 2>/dev/null
if [ \$? -eq 0 ]; then
    echo "✓ maxwell数据库正常"
else
    echo "✗ maxwell数据库异常"
fi

# 检查Maxwell进程
echo "4. 检查Maxwell进程..."
if pgrep -f maxwell > /dev/null; then
    echo "✓ Maxwell正在运行，PID: \$(pgrep -f maxwell)"
else
    echo "✗ Maxwell未运行"
fi

echo "测试完成"
EOF
    
    chmod +x /opt/maxwell/test_maxwell.sh
    echo -e "${GREEN}✓ 测试脚本已创建${NC}"
}

# 显示使用说明
show_usage() {
    echo ""
    echo -e "${CYAN}==================================${NC}"
    echo -e "${CYAN}Maxwell配置完成！${NC}"
    echo -e "${CYAN}==================================${NC}"
    echo ""
    echo -e "${YELLOW}使用说明:${NC}"
    echo "1. 启动Maxwell: /opt/maxwell/start_maxwell.sh"
    echo "2. 停止Maxwell: /opt/maxwell/stop_maxwell.sh"
    echo "3. 测试连接: /opt/maxwell/test_maxwell.sh"
    echo "4. 查看日志: tail -f /opt/maxwell/maxwell.log"
    echo "5. 编辑配置: vim /opt/maxwell/config.properties"
    echo ""
    echo -e "${YELLOW}配置文件位置:${NC}"
    echo "/opt/maxwell/config.properties"
    echo ""
    echo -e "${YELLOW}输出目标配置:${NC}"
    echo "当前配置为输出到Kafka，如需修改请编辑配置文件"
    echo "支持的输出目标: kafka, file, redis, rabbitmq"
    echo ""
    echo -e "${GREEN}现在可以启动Maxwell了！${NC}"
}

# 主函数
main() {
    check_root
    check_java
    install_maxwell
    setup_database_permissions
    generate_config
    test_connection
    create_startup_script
    create_test_script
    show_usage
}

# 执行主函数
main 